package com.zwx.service;

import com.zwx.response.ResultBean;
import com.zwx.response.ResultCode;
import com.zwx.utils.MyShortUrlUtil;
import com.zwx.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Title 短网址转换服务
 */
@Service
public class ShortUrlConvertService {
    @Value("${domain}")
    private String domain;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 短网址加密生成(为空默认有效期7天，可自定义时长)
     *
     * @param urlLong
     * @param days
     * @return
     */
    public ResultBean shorten(String urlLong, Integer days) {
        days = days == null ? 7 : days;
        //加密短网址，返回短网址URL数组
        String shortUrl = generateUrl(urlLong, days, TimeUnit.DAYS);
        domain = domain.endsWith("/") ? domain : domain + "/";
        shortUrl = domain + shortUrl;
        ResultBean resultBean = new ResultBean<>(shortUrl);
        if (shortUrl == null) {
            resultBean = new ResultBean(ResultCode.FAIL, "网址非法，转换失败！");
        }
        return resultBean;
    }

    /**
     * 短网址解密
     *
     * @param shortUrl
     * @return
     */
    public ResultBean shortde(String shortUrl) {
        shortUrl = shortUrl.replaceAll(domain, "");
        //判断网址是否存在
        String url = redisUtil.get("shortUrl:" + shortUrl);
        ResultBean resultBean = new ResultBean<>(url);
        if (url == null) {
            resultBean = new ResultBean(ResultCode.FAIL, "短网址非法，解析失败！");
        }
        return resultBean;
    }


    private String generateUrl(String urlLong, Integer times, TimeUnit timeUnit) {
        //加密短网址，返回短网址URL数组
        String[] shortUrls = MyShortUrlUtil.shortUrl(urlLong);

        //循环获取加密url
        for (String shortUrl : shortUrls) {
            //判断短网址是否存在
            Boolean exists = redisUtil.exists("shortUrl:" + shortUrl);
            if (exists) {
                //判断网址是否存在
                String url = redisUtil.get("shortUrl:" + shortUrl);
                if (urlLong.equals(url)) {
                    redisUtil.set("shortUrl:" + shortUrl, urlLong);
                    if (times != 0) {
                        redisUtil.expire("shortUrl:" + shortUrl, times, timeUnit);
                    }
                    return shortUrl;
                }
                continue;
            }
            redisUtil.set("shortUrl:" + shortUrl, urlLong);
            if (times != 0) {
                redisUtil.expire("shortUrl:" + shortUrl, times, timeUnit);
            }
            return shortUrl;
        }
        return null;
    }
}
